import { getUsersApi } from "@/api";
import type { getAiReWriteTaskResidueNumApi } from "@/api/aiTask";
import { ES } from "@/api/esSearch";
import mainStore from "@/stores/main";
import type { ExportSearchApi } from "@/typing/common";
import { Button, message } from "ant-design-vue";
import dayjs from "dayjs";
/**
 *
 * @param searchBody Ref<Record<string, any>> 搜索体
 * @param api        导出的API接口
 * @param filePrefix 文件名前缀
 * @param blobType   blob类型
 * @returns
 */
export function useExportSearch<A extends ExportSearchApi>(
    searchBody: Ref<Record<string, any>>,
    api: A,
    filePrefix: string = "",
    blobType: string = "application/csv;charset=utf-8"
) {
    return function () {
        api(searchBody.value)
            .then((res) => {
                const blob = new Blob([res.data], { type: blobType });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url;
                a.download = filePrefix + +new Date() + ".csv";
                a.click();
                URL.revokeObjectURL(url);
            })
            .catch(() => {
                message.error("下载失败!");
            });
    };
}
export function downloadFile(prefix: string, data: string,type:string =  "application/json",suffix:string=".json") {
    const blob = new Blob([data], { type });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = prefix + +new Date() + suffix;
    a.click();
    URL.revokeObjectURL(url);
}
export function useSpinLoadingState() {
    const viewLoading = ref(false);
    const spinStyle = computed(() => ({ height: window.innerHeight - 100 + "px" }));
    return {
        viewLoading,
        spinStyle
    };
}
const $store = mainStore();
export function useAdminShow(): boolean {
    return $store.userInfo.level === 1;
}
export function useUserName(): string {
    return $store.username;
}
export const filterOption = (input: string, option: SelectOptionItem) => {
    return (
        (option.value as string).toUpperCase().indexOf(input.toUpperCase()) >= 0 ||
        (option.label as string).toUpperCase().indexOf(input.toUpperCase()) >= 0
    );
};
// 创建剩余数Button组件
export const createResidueNumButton = (funcApi: typeof getAiReWriteTaskResidueNumApi, tableRow: any) => {
    return h(
        Button,
        {
            type: "link",
            onClick() {
                funcApi(tableRow.record.name, tableRow.record.add_time).then((res: any) => {
                    message.info("加载成功!");
                    tableRow.record.residue_num = res.data.num;
                });
            }
        },
        { default: () => "获取剩余数" }
    );
};

export function useDateRangePresets() {
    return ref([
        {
            label: "今天",
            value: [
                dayjs().set("hour", 0).set("minute", 0).set("second", 0),
                dayjs().set("hour", 23).set("minute", 59).set("second", 59)
            ]
        },
        { label: "最近一天", value: [dayjs().add(-1, "d"), dayjs()] },
        { label: "最近三天", value: [dayjs().add(-3, "d"), dayjs()] },
        { label: "最近一周", value: [dayjs().add(-7, "d"), dayjs()] },
        { label: "最近两周", value: [dayjs().add(-14, "d"), dayjs()] },
        { label: "最近一个月", value: [dayjs().add(-30, "d"), dayjs()] },
        { label: "最近三个月", value: [dayjs().add(-90, "d"), dayjs()] }
    ]);
}
const es = new ES("90");

// 获取所有网站列表
export function useGetWebsiteDomains() {
    const websiteMap = ref<Record<string, number>>({});
    const websiteOptions = ref<SelectOption>([]);
    es.search("websites", { _source: ["pc_domain", "id"], size: 100000 }).then((res) => {
        websiteOptions.value = res.data.data.hits.hits.map((item: any) => {
            const pcDomain = item["_source"]["pc_domain"];
            websiteMap.value[pcDomain] = item["_source"]["id"];
            return {
                label: pcDomain,
                value: pcDomain
            };
        });
    });
    return {
        websiteMap,
        websiteOptions
    };
}
// 获取所有网站列表
export async function useGetWebsiteIds(query: Record<string, any>) {
    const ids: Array<number> = [];
    const res = await es.search("websites", { query, _source: ["id"], size: 100000 });
    for (const item of res.data.data.hits.hits) {
        ids.push(item["_source"]["id"]);
    }
    return ids;
}
export function useCommonOptions() {
    const linkStoreOptions = [
        {
            label: "我方网站",
            value: 1
        },
        {
            label: "其他网站",
            value: 2
        }
    ];
    return { linkStoreOptions };
}
const userOptions = ref<SelectOption>([]);
export const useUserOptions = (filterUsernames:string[] = [])=>{
    if(!userOptions.value.length){
        getUsersApi().then((res) => {
            if (res.data.code === 200) {
                userOptions.value = [{ label: "请选择", value: 0 }].concat(
                    res.data.data.filter((item:any)=>!filterUsernames.includes(item.username) ).map((item: any) => ({ label: item.author, value: item.id }))
                );
            }
        });
    }
    return userOptions
}